<template>
  <div class="page-container">
    <el-form label-position="top" class="custom-form">
      <el-form-item label="图片目录" class="form-item-group">
        <el-input
          v-model="imageDir"
          placeholder="选择包含图片的目录"
          readonly
          class="form-input"
        >
          <template #append>
            <el-button
              type="primary"
              class="browse-btn"
              @click="selectImageDirFn"
              >浏览</el-button
            >
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="输出目录" class="form-item-group">
        <el-input
          v-model="outputDir"
          placeholder="选择输出目录"
          readonly
          class="form-input"
        >
          <template #append>
            <el-button
              type="primary"
              class="browse-btn"
              @click="selectOutputDirFn"
              >浏览</el-button
            >
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="PDF名称" class="form-item-group">
        <el-input
          v-model="customPdfName"
          placeholder="输出PDF的名称"
          class="form-input"
        />
      </el-form-item>

      <el-form-item label="缩放模式" class="form-item-group">
        <el-select v-model="scaleMode" style="width: 100%" class="form-select">
          <el-option
            v-for="option in scaleModeAry"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="progress-section">
        <div class="progress-label">处理进度</div>
        <el-progress
          :percentage="progress"
          :status="progressStatus"
          :text-inside="true"
          :stroke-width="18"
          class="custom-progress"
        />
      </el-form-item>

      <el-form-item v-if="statusVisible" class="status-section">
        <el-alert
          :title="statusMessage"
          :type="statusType"
          show-icon
          class="status-alert"
        />
      </el-form-item>

      <el-form-item class="button-section">
        <el-button
          type="success"
          class="primary-btn"
          @click="createPdfFn"
          :disabled="isProcessing"
          >开始创建</el-button
        >
        <el-button type="default" class="secondary-btn" @click="clearFormFn"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';

// 响应式数据
const imageDir = ref('');
const outputDir = ref('');
const customPdfName = ref('');
const scaleMode = ref('fitWidth');
const progress = ref(0);
const progressStatus = ref('');
const statusMessage = ref('');
const statusType = ref('info');
const statusVisible = ref(false);
const isProcessing = ref(false);

// 缩放模式选项
const scaleModeAry = reactive([
  { label: '适应宽度', value: 'fitWidth' },
  { label: '适应高度', value: 'fitHeight' },
  { label: '适应页面', value: 'fitBoth' },
]);

// 选择图片目录
const selectImageDirFn = async () => {
  const paths = await window.electronAPI.openDirectoryDialog();
  if (paths.length > 0) {
    imageDir.value = paths[0];
  }
};

// 选择输出目录
const selectOutputDirFn = async () => {
  const paths = await window.electronAPI.openDirectoryDialog();
  if (paths.length > 0) {
    outputDir.value = paths[0];
  }
};

// 显示状态信息
const showStatusFn = (message, type) => {
  statusMessage.value = message;
  statusType.value = type;
  statusVisible.value = true;
};

// 更新进度值
const progressValueUpdateFn = value => {
  progress.value = value;
  if (value === 100) {
    progressStatus.value = 'success';
  } else {
    progressStatus.value = '';
  }
};

// 开始创建PDF
const createPdfFn = async () => {
  if (!imageDir.value) {
    showStatusFn('请选择图片目录', 'error');
    return;
  }

  if (!outputDir.value) {
    showStatusFn('请选择输出目录', 'error');
    return;
  }

  // 重置进度状态
  isProcessing.value = true;
  progress.value = 0;
  progressStatus.value = '';
  statusVisible.value = false;
  showStatusFn('开始创建PDF...', 'info');

  try {
    const result = await window.electronAPI.createPdf({
      imageDir: imageDir.value,
      outputDir: outputDir.value,
      notFullWidthDir: outputDir.value + '/not_full_width',
      maxPagesPerPdf: 1000,
      useA4Size: true,
      a4Width: 595,
      a4Height: 842,
      supportedFormats: ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.tif', '.webp'],
      scaleMode: scaleMode.value,
      forceRegenerate: true,
      customPdfName: customPdfName.value,
    });
    let statusMessage = `PDF创建成功！共处理 ${result.batches} 个批次，成功 ${result.successful} 个批次`;
    if (result.outputPaths && result.outputPaths.length > 0) {
      statusMessage += `，文件保存于: ${result.outputPaths.join('；')}`;
    }
    showStatusFn(statusMessage, 'success');
    progressValueUpdateFn(100);
  } catch (error) {
    showStatusFn('创建失败: ' + error.message, 'error');
  } finally {
    isProcessing.value = false;
  }
};

// 清空表单
const clearFormFn = () => {
  imageDir.value = '';
  outputDir.value = '';
  customPdfName.value = '';
  scaleMode.value = 'fitWidth';
  progress.value = 0;
  progressStatus.value = '';
  statusVisible.value = false;
};

// 监听进度更新
const progressUpdateFn = progress => {
  if (progress.type === 'create-pdf') {
    if (progress.error) {
      showStatusFn('处理失败: ' + progress.error, 'error');
      isProcessing.value = false;
      return;
    }
    progressValueUpdateFn(progress.progress);
  }
};

// 生命周期钩子
onMounted(() => {
  window.electronAPI.onProgressUpdate(progressUpdateFn);
});

onUnmounted(() => {
  window.electronAPI.removeProgressListener();
});
</script>

<style scoped>
</style>
